<template>
    <div v-loading="mapLoading" class="mapContainer">
        <el-dialog :visible.sync="dialogVisible" width="920px">
          <div class="address-content-wrap">
             <div id="container" style="width: 100%;height: 600px;" />
             <div class="search-view">
                
               <div class="search-input">
                  <el-input id="start-input" v-model="place" class="w-1/3" clearable placeholder="请输入关键字检索" @keyup.enter.native="handleChange('click')" @input="handleChange('input')">
                        <el-button slot="append" v-loading="isLoading" icon="el-icon-search" @click="handleChange('click')" />
                  </el-input>
                  <ul v-if="addressArr.length !== 0 " class="recommend">
                      <li v-for="(start,index) in addressArr" :key="index" @click="selectStart(start)">{{ start.name }}<span>{{ start.district }}</span></li>
                  </ul>
               </div>
             </div>
             <div class="botom-panel">
                <div class="title">当前标记点位置</div>
                <el-form ref="mapForm" :model="form" :rules="rules" inline size="mini">
                  <el-form-item label="经度" prop="lng">
                      <el-input v-model="form.lng" clearable @input="inputChange" />
                  </el-form-item>
                  <el-form-item label="纬度" prop="lat">
                      <el-input v-model="form.lat" clearable @input="inputChange" />
                  </el-form-item>
                  <el-form-item label-width="0">
                    <BaseButton @click="getlatandlng">确定</BaseButton>
                  </el-form-item>
                </el-form>
             </div>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { mapKey } from '@/config/settings'
const latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/
const longreg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/

// 纬度校验
function validateLat(rule, value, callback) {
    if (!latreg.test(value)) {
        callback(new Error('请输入正确的纬度'))
    } else {
        callback()
    }
}
// 经度校验
function validateLng(rule, value, callback) {
    if (!longreg.test(value)) {
        callback(new Error('请输入正确的经度'))
    } else {
        callback()
    }
}
export default {
    name: 'AddressDialog',
    props: {
        location: {
            type: Object,
            default: () => {
                return {
                    lat: null,
                    lng: null
                } 
            }
        }
    },
    data() {
        return {
            isLoading: false,
            mode: 1, 
            dialogVisible: false,
            mapLoading: true,
            map: {},
            AMap: {},
            place: '',
            form: {
                lat: null,
                lng: null
            },
            addressArr: [],
            autoLat: '',
            autoLng: '',
            makeLat: '',
            makeLng: '',
            autoMarker: null,
            makeMarker: null,
            makeIcon: null,
            autoIcon: null,
            rules: Object.freeze({ 
                lat: [
                    { required: true, trigger: 'blur', message: '请输入纬度' },
                    { validator: validateLat, trigger: 'change' }
                ],
                lng: [
                    { required: true, trigger: 'blur', message: '请输入经度' },
                    { validator: validateLng, trigger: 'change' }
                ]
            })
        }
    },
    watch: {
        'form.lat'() {
            if (this.form.lng && this.form.lat) {
                if (longreg.test(this.form.lng) && latreg.test(this.form.lat)) {
                    this.map.setCenter && this.changeCenter()
                }
            }
        },
        'form.lng'() {
            if (this.form.lng && this.form.lat) {
                if (longreg.test(this.form.lng) && latreg.test(this.form.lat)) {
                    this.map.setCenter && this.changeCenter()
                }
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.form = this.location
            this.init()
        })
    },
    methods: {
        // 设置地图中心点
        changeCenter(lng = this.form.lng, lat = this.form.lat) {
            // 传入经纬度，设置地图中心点
            const position = [lng, lat] // 标准写法
            // 简写 var position = [116, 39]; 
            this.map.setCenter(position) 
        },
        // 经纬度输入事件
        inputChange(val) {
            if (this.form.lng && this.form.lat) {
                if (longreg.test(this.form.lng) && latreg.test(this.form.lat)) {
                    // 如果之前有标记点先移除
                    if (this.makeLng && this.makeLat) {
                        this.map.remove(this.makeMarker)
                    }
                    this.makeLat = this.form.lat
                    this.makeLng = this.form.lng
                    // 增加新的标记点
                    this.addMakeMarker(this.form.lng, this.form.lat)
                }
            } 
        },
        // 输入事件
        handleChange(type) {
            console.log('12')
            // 输入的时候只触发poi检索
            if (type === 'input') {
                if (this.mode === 1) {
                    // poi检索
                    this.poiSearch()
                }
            }
        },
        // poi检索
        poiSearch() {
            const _this = this
            if (!this.place) {
                this.addressArr = []
            } else if (this.place === '#') {
                this.$message({
                    showClose: true,
                    message: '暂无查询结果，请输入其他地点查询！',
                    type: 'warning'
                })
            } else {
                const autoComplete = new this.AMap.AutoComplete()
                autoComplete.search(this.place, function(status, result) {
                    if (status === 'complete' && result) {
                        _this.addressArr = result.tips
                    } else if (!_this.place) { // 请求会存在延时问题
                        _this.addressArr = []
                    } else {
                        _this.$message({
                            showClose: true,
                            message: '暂无查询结果，请输入其他地点查询！',
                            type: 'warning'
                        })
                    }
                })
            }
        },
        // 检索选中事件
        selectStart(val) {
            if (val.id) {
                // 如果之前有标记点先移除
                if (this.autoLng && this.autoLat) {
                    this.map.remove(this.autoMarker)
                }
                if (!val.location) {
                    this.form.lat = null
                    this.form.lng = null
                    this.$message.warning('当前位置无具体坐标！')
                    return
                }
                this.autoLat = val.location.lat
                this.autoLng = val.location.lng
                this.form.lat = val.location.lat
                this.form.lng = val.location.lng
               
                this.place = val.name
                this.addressArr = []
                // 增加新的标记点
                this.autoMarker = new this.AMap.Marker({
                    position: new this.AMap.LngLat(this.autoLng, this.autoLat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                    icon: this.autoIcon,
                    offset: new this.AMap.Pixel(-15, -33)
                })
                this.map.add(this.autoMarker)
                // 设置地图中心点
                this.changeCenter(this.autoLng, this.autoLat)
            } else {
                this.$message({
                    message: '请选择具体的位置！',
                    type: 'warning'
                })
            }
        },
        // 地图初始化
        init() {
            AMapLoader.load({
                key: mapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
                version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    'AMap.ToolBar',
                    'AMap.Scale',
                    'AMap.Geolocation',
                    'AMap.LngLat',
                    'AMap.PlaceSearch',
                    'AMap.AutoComplete'
                ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })
                .then((AMap) => {
                    this.AMap = AMap
                    this.map = new AMap.Map('container', { zoom: 11, viewMode: '2D' })
                    // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
                    const toolBar = new AMap.ToolBar({
                        position: {
                            top: '80px',
                            left: '20px'
                        }
                    })
                    // this.map.remove(this.autoMarker)
                    this.map.addControl(toolBar)
                    // 创建图标
                    this.autoIcon = new this.AMap.Icon({
                        size: new this.AMap.Size(25, 32), // 图标尺寸
                        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                        imageOffset: new this.AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
                        imageSize: new this.AMap.Size(25, 32) // 根据所设置的大小拉伸或压缩图片
                    })
                    this.makeIcon = new this.AMap.Icon({
                        size: new this.AMap.Size(25, 34), // 图标尺寸
                        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
                        imageOffset: new this.AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
                        imageSize: new this.AMap.Size(25, 34) // 根据所设置的大小拉伸或压缩图片
                    })
                    // 增加新的标记点
                    if (this.form.lng && this.form.lat) {
                        this.autoMarker = new this.AMap.Marker({
                            position: [this.form.lng, this.form.lat], // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                            icon: this.autoIcon,
                        })
                        this.map.add(this.autoMarker)
                    }
                    
                    this.map.setFitView()
                    // 点击地图增加标记点
                    this.map.on('click', (e) => {
                        // 如果之前有标记点先移除
                        if (this.makeLng && this.makeLat) {
                            this.map.remove(this.makeMarker)
                        }
                        this.makeLat = e.lnglat.lat
                        this.makeLng = e.lnglat.lng
                        
                        // 增加新的标记点
                        this.addMakeMarker(e.lnglat.lng, e.lnglat.lat)
                        // 设置输入框经纬度值
                        this.form.lat = this.makeLat
                        this.form.lng = this.makeLng
                    })
                    this.mapLoading = false
                })
                .catch((e) => {
                    console.log(e)
                    this.mapLoading = false
                })
        },
        // 添加手动标记点
        addMakeMarker(lng, lat) {
            // 增加新的标记点
            this.makeMarker = new this.AMap.Marker({
                position: [lng, lat], // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                icon: this.makeIcon,
                offset: new this.AMap.Pixel(-15, -35)
            })
            this.map.add(this.makeMarker)
        },
        // 显示弹框
        show() {
            this.dialogVisible = true
        },
        // 传递经纬度数据
        getlatandlng() {
            this.$refs['mapForm'].validate(valid => {
                if (valid) {
                    this.$emit('handdata', this.form)
                    this.dialogVisible = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.address-content-wrap{
  position: relative;
  width: 100%;
  overflow: hidden;
  .search-view{
    box-sizing: border-box;
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    padding: 16px 16px;
    width: 100%;
    .search-input{
      flex-grow: 1;
      margin-right: 20px;
      .recommend{
          position:absolute;
          z-index: 30000;
          margin: 0;
          padding: 0;
          width: inherit;
          background-color: #fff;
          border: 1px solid #d1d1d1;
          li{
              font-size: 13px;
              padding: 4px 8px;
              cursor: pointer;
              line-height: 19px;
              span{
                color: #c1c1c1;
                padding-left: 4px;
                font-size: 12px;
              }
              &:hover{
                    background-color: #cae1ff;
              }
          }
      }
    }
  }
  .botom-panel{
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 150px;
    box-sizing: border-box;
    padding: 20px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    .title{
      margin-bottom: 30px;
      color: #AAAAAA;
    }
  }
}
::v-deep {
    .amap-logo {
        display: none !important;
        visibility: hidden !important;
    }
    .amap-copyright {
        display: none !important;
        visibility: hidden !important;
    }
    .amap-info-content {
        background: #222;
        color: #fff;
        font-size: 14px;
        border-radius: 5px;
        padding-left: 18px;
    }
    .bottom-center .amap-info-sharp {
        border-top: 8px solid #222;
    }
    .amap-info-close {
        display: none !important;
    }
}
</style>
<style lang="scss">
.mapContainer{
  .el-dialog__body{
    padding: 34px 0 0 0 !important;
  }
}
</style>

